package
{
	import flash.events.Event;
	
	import mx.controls.DataGrid;
	import mx.controls.dataGridClasses.DataGridItemRenderer;
	import mx.controls.dataGridClasses.DataGridListData;
	import mx.events.ListEvent;

	public class BlinkWhenChangedRenderer extends DataGridItemRenderer
	{
		
		public function BlinkWhenChangedRenderer()
		{
			super();
			
		}
		
		private var lastUID:String = null;
		
		private var originalValue : Object = null;
		private var currentRowValue : Object = null;
		
		
		/**
		 *  DataGridItemRenderer extends TextField and has a slightly different
		 *  validation mechanism than UIComponent-based widgets.  All visuals
		 *  are resolved within the validateNow call.  We apply the background
		 *  here
		 */
		override public function validateNow():void
		{
			super.validateNow();
			
			if (!listData) 
			{
				// item renderers are recycled so you have to make sure
				// that all code paths lead to a known state.
				background = false;
				return;
			}
			
			var dgListData:DataGridListData = listData as DataGridListData;
			var dataGrid:DataGrid = dgListData.owner as DataGrid;

			init();

			if( currentRowValue == null )
				currentRowValue = dataGrid.dataProvider[ dgListData.rowIndex ];
			
			var column:BlinkWhenChangedColumn = dataGrid.columns[dgListData.columnIndex];
			if (dgListData.uid == lastUID)
			{
				if( originalValue == null ){
					originalValue = currentRowValue[ dgListData.dataField ];
				}
				if (dgListData.label != originalValue )
				{
					currentRowValue.isChanged = true;
				}
			}
			lastUID = dgListData.uid;

			if ( currentRowValue != null && currentRowValue.isChanged )
			{
				background = true;
				backgroundColor = column.blinkColor;
//				column.backgroundColor = 0xFFFF00;
			}
		}
		
		private var dg:DataGrid;
		
		private function init():void
		{
			dg = listData.owner as DataGrid;
			dg.addEventListener(ListEvent.CHANGE, updateSelected);
		}
		
		override public function set data(value:Object):void
		{
			super.data = value;
			
			if(value)
			{
				var dglistData:DataGridListData = listData as DataGridListData;
				if(value[dglistData.dataField])
					this.text = value[dglistData.dataField];
				updateSelected();
			} 
		}
		
		private function updateSelected(e:Event = null):void
		{
			if(!data || !dg)
				return;
			
			if(dg.selectedItem == data)
			{
				//This row is selected update stuff
				setStyle("fontWeight", "bold");
			}
			else
			{
				//This row is not selected reset stuff
				setStyle("fontWeight", "normal");
			}
		}
		
	}
	
}